<template lang="pug">
.view.cp-credential-man-register.fix-flex-pos
  el-form.cl-search(:inline="true")
    el-form-item
      el-input(v-model="productName", placeholder="产品名称", style="width: 160px")
    el-form-item(label="供应商 : ")
      el-select(v-model="supplyName", placeholder="请选择", style="width: 120px")
        el-option(
          v-for="item in supplySelectAll",
          :key="item.value", :label="item.name",
          :value="item.value")
    //- el-form-item(label="提前预警时间")
    //-   el-input-number(v-model="warnDays", :controls="false", style="width: 80px")
    //-   span(style="margin-left: 8px") 天
    el-form-item
      el-button(type="primary", @click="searchRegisters") 搜索
    el-form-item
      el-button(type="primary", @click="resetSearch", plain) 重置
    el-form-item
      el-button(type="primary", @click="addRegister", v-show="!registerList.length", plain) 初始化
  //- 列表
  .cl-table
    el-table(
      :data="registerList",
      highlight-current-row
      height="100%"
      size="mini"
      v-loading="loadingRegisters")
      el-table-column(align="center", show-overflow-tooltip, type="index", :index="indexMethod", label="序号", :fixed="true")
      el-table-column(align="center", show-overflow-tooltip, prop="registNo", label="编号")
        template(slot-scope="scope")
          el-input(v-model="scope.row.registNo", v-show="scope.row.isEdit")
          span(v-text="scope.row.registNo", v-show="!scope.row.isEdit")
      el-table-column(align="center", show-overflow-tooltip, prop="productName", label="名称")
        template(slot-scope="scope")
          el-input(v-model="scope.row.productName", v-show="scope.row.isEdit")
          span(v-text="scope.row.productName", v-show="!scope.row.isEdit")
      el-table-column(align="center", show-overflow-tooltip, prop="modelNo", label="型号")
        template(slot-scope="scope")
          el-select(v-model="scope.row.modelNo", v-show="scope.row.isEdit")
            el-option(
              v-for="item in modelSelect",
              :key="item.value", :label="item.name",
              :value="item.value")
          span(v-show="!scope.row.isEdit") {{ scope.row.modelNo | compare-list(modelSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="owner", label="持证公司")
        template(slot-scope="scope")
          el-select(v-model="scope.row.owner", v-show="scope.row.isEdit")
            el-option(
              v-for="item in supplySelect",
              :key="item.value", :label="item.name",
              :value="item.value")
          span(v-show="!scope.row.isEdit") {{ scope.row.owner | compare-list(supplySelect) }}
        //- template(slot-scope="scope")
        //-   el-input(v-model="scope.row.owner", v-show="scope.row.isEdit")
        //-   span(v-text="scope.row.owner", v-show="!scope.row.isEdit")
      el-table-column(align="center", show-overflow-tooltip, prop="desc", label="描述")
        template(slot-scope="scope")
          el-input(v-model="scope.row.desc", v-show="scope.row.isEdit")
          span(v-text="scope.row.desc", v-show="!scope.row.isEdit")
      el-table-column(align="center", prop="issueDate", label="发证日期", min-width="96px")
        template(slot-scope="scope")
          el-date-picker(v-model="scope.row.issueDate", v-show="scope.row.isEdit", type="date" ,placeholder="选择日期", style="width: 100%", :clearable="false")
          span(v-show="!scope.row.isEdit") {{ scope.row.issueDate | date-locale }}
      el-table-column(align="center", prop="expireDate", label="到期日期", min-width="96px")
        template(slot-scope="scope")
          el-date-picker(v-model="scope.row.expireDate", v-show="scope.row.isEdit", type="date" ,placeholder="选择日期", style="width: 100%", :clearable="false")
          span(v-show="!scope.row.isEdit") {{ scope.row.expireDate | date-locale }}
      el-table-column(align="center", show-overflow-tooltip, prop="period", label="周期")
        template(slot-scope="scope")
          el-input(v-model="scope.row.period", v-show="scope.row.isEdit")
          span(v-text="scope.row.period", v-show="!scope.row.isEdit")
      el-table-column(align="center", show-overflow-tooltip, prop="attachList", label="附件")
        template(slot-scope="scope")
          el-upload(
            :ref="`upload${scope.$index}`"
            v-show="scope.row.isEdit"
            action="https://jsonplaceholder.typicode.com/posts/"
            :limit="1"
            :show-file-list="false"
            :before-upload="uploadFileBefore"
            :on-success="uploadFileSucc"
            :on-error="uploadFileFail")
            i.el-icon-plus(@click="uploadFile(scope.$index)")
          a(v-if="scope.row.attachList && scope.row.attachList.length", v-show="!scope.row.isEdit", target="_blank", :href="scope.row.attachList[0].url") {{ scope.row.attachList[0].name }}
      el-table-column(align="center", show-overflow-tooltip, prop="remark", label="备注")
        template(slot-scope="scope")
          el-input(v-model="scope.row.remark", v-show="scope.row.isEdit")
          span(v-text="scope.row.remark", v-show="!scope.row.isEdit")
      el-table-column(align="center", label="操作", width="96px")
        template(slot-scope="scope")
          el-tooltip(content="编辑", v-show="!scope.row.isEdit", @click.native="editRegister(scope.$index)")
            i.icon-act.el-icon-edit
          el-tooltip(content="添加", v-show="!scope.row.isEdit", @click.native="addRegister(scope.$index)")
            i.icon-act.el-icon-plus
          el-tooltip(content="删除", v-show="!scope.row.isEdit", @click.native="deleteRegister(scope.$index)")
            i.icon-act.el-icon-delete
          el-tooltip(content="确定", v-show="scope.row.isEdit", @click.native="insertRegister(scope.$index)")
            i.icon-act.el-icon-check
          el-tooltip(content="取消", v-show="scope.row.isEdit", @click.native="cancleRegister(scope.$index)")
            i.icon-act.el-icon-close
  //- 分页
  el-pagination.cl-pagination(
    layout="total, prev, pager, next, jumper",
    @current-change="changeRegisterPage",
    :current-page.sync="currentPage",
    :page-size="pageSize",
    :total="registerListTotal")
</template>

<script>
import { mapGetters } from 'vuex';
import validate from '@/utils/validate';
import ManApi from '@/api/manage';

const { isEmpty } = validate;

export default {
  name: 'creregister',
  data() {
    return {
      // search
      productName: null,
      supplyName: null,
      // warnDays: null,
      // table
      registerList: [],
      registerListBC: [],
      registerListTotal: 1,
      loadingRegisters: true,
      currentPage: 1,
      pageSize: 20,
      // list
      modelSelect: [
        { value: 0, name: '已结单' },
        { value: 1, name: '已下单' }
      ],
      scaleSelect: [
        { value: 0, name: '小' },
        { value: 1, name: '中' },
        { value: 2, name: '大' }
      ]
    };
  },
  computed: {
    ...mapGetters(['empSelect', 'empSelectAll', 'supplySelect', 'supplySelectAll'])
  },
  methods: {
    indexMethod (i) {
      const size = this.pageSize || 20;
      return ((this.currentPage - 1) * size) + (i + 1);
    },
    resetSearch () {
      this.productName = null;
      this.supplyName = null;
      // this.warnDays = null;
    },
    makeSearch () {
      const params = {};
      if (!isEmpty(this.productName)) {
        params.productName = this.productName;
      }
      if (!isEmpty(this.supplyName)) {
        params.owner = this.supplyName;
      }
      // if (!isEmpty(this.warnDays)) {
      //   params.createUser = this.warnDays;
      // }

      return params;
    },
    loadRegisterList (query) {
      const params = query || {};

      ManApi.getCredentialRegister(params).then((result) => {
        if (!result.status) {
          this.registerList = result.obj.records;
          this.registerListTotal = result.obj.totalNum;
        } else {
          this.registerList = [];
          this.registerListTotal = 1;
          this.currentPage = 1;
          this.$message.error(result.comment);
        }
        this.loadingRegisters = false;
      }).catch((error) => {
        this.loadingRegisters = false;
        console.log(JSON.stringify(error));
      });
    },
    searchRegisters () {
      const params = this.makeSearch();
      this.loadingRegisters = true;

      this.loadRegisterList(params);
    },
    changeRegisterPage (currentPage) {
      const params = this.makeSearch();
      params.pageNum = currentPage;

      this.loadingRegisters = true;
      this.loadRegisterList(params);
    },
    // 监听设备列表
    addRegister (index) {
      const newObj = {
        isEdit: true,
        attachList: []
      };
      if (isEmpty(index)) {
        this.registerList.push(newObj);
      } else {
        this.registerList.splice((index + 1), 0, newObj);
      }
    },
    editRegister (index) {
      this.registerListBC[index] = JSON.parse(JSON.stringify(this.registerList[index]));
      this.$set(this.registerList[index], 'isEdit', true);
    },
    deleteRegister (index) {
      const register = this.registerList[index];
      if (register.id) {
        this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          ManApi.deleteCredentialRegister({ id: register.id }).then((res) => {
            if (res.status === 0) {
              this.registerList.splice(index, 1);
              this.registerListBC[index] = null;
              this.$message.success('删除成功');
            } else {
              this.$message.error(res.comment || '删除失败');
            }
          });
        }).catch(() => {
          this.$message.info('已取消删除');
        });
      } else {
        this.registerList.splice(index, 1);
        this.registerListBC[index] = null;
      }
    },
    insertRegister (index) {
      if (this.creditUrl) {
        const attach = this.registerList[index].attachList[0];
        if (!attach) {
          this.registerList[index].attachList[0] = {};
        }
        this.registerList[index].attachList[0].url = this.creditUrl;
        this.registerList[index].attachList[0].name = this.creditName;
      }

      ManApi.saveCredentialRegister(this.registerList[index]).then((result) => {
        if (!result.status) {
          this.$message.success('保存成功');
          if (!this.registerList[index].id) {
            this.registerList[index].id = result.obj;
          }
          this.registerList[index].isEdit = false;
        } else {
          this.$message.warning(result.comment);
        }
      });
    },
    cancleRegister (index) {
      if (this.registerListBC[index]) {
        this.$set(this.registerList, `${index}`, this.registerListBC[index]);
      } else {
        this.deleteRegister(index);
      }
    },
    // 附件上传
    uploadFile (index) {
      // 每次上传前清空上次文件
      this.$refs[`upload${index}`].clearFiles();
    },
    uploadFileBefore (file) {
      console.log(file);
      this.loading = this.$loading({
        fullscreen: true,
        text: '努力上传中, 请稍等...',
        background: 'transparent'
      });
    },
    uploadFileSucc (res, file) {
      if (file) {
        if (this.loading) {
          this.loading.close();
        }
        this.$message.success(`证书资质 ${file.name} 上传成功, 点击确认即可查看上传文件`);
        this.creditUrl = file.url;
        this.creditName = file.name;
      }
    },
    uploadFileFail (res, file) {
      if (file) {
        if (this.loading) {
          this.loading.close();
        }
        this.$message.warning(`证书资质 ${file.name} 上传失败, 请稍后再试`);
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next();
  },
  created () {
  },
  mounted () {
    this.loadRegisterList();
  }
};
</script>

<style lang="sass">
@import "../../../../styles/utils"
$SEARCHHEIGHT: 56px
$PAGEHEIGHT: 56px
.cp-credential-man-register
  .cl-search
    height: $SEARCHHEIGHT
    overflow-x: auto
    overflow-y: hidden
    padding: 12px 0 12px 16px
    .el-form-item
      margin-right: 14px
    .el-form-item__label
      padding-right: 6px
  .cl-table
    position: absolute
    top: $SEARCHHEIGHT
    bottom: $PAGEHEIGHT
    left: 16px
    right: 16px
    overflow: auto
    table
      &::before
        display: none
      .icon-act
        font-size: 16px
        margin-left: 3px
        margin-right: 3px
  .cl-pagination
    position: absolute
    bottom: 12px
    left: 0
    right: 0
    text-align: center
</style>
